using System.ComponentModel.DataAnnotations;
using OfficeOpenXml;
using UserManagement.Models;

namespace UserManagement.Services;

public class ExcelImportService : IExcelImportService
{
    public ExcelImportResult ImportUsers(Stream excelStream)
    {
        var result = new ExcelImportResult();
        using (var package = new ExcelPackage(excelStream))
        {
            var worksheet = package.Workbook.Worksheets[0];
            int rowCount = worksheet.Dimension.Rows;

            for (int row = 2; row <= rowCount; row++) // 从第2行开始（跳过标题）
            {
                var user = new User
                {
                    Username = worksheet.Cells[row, 1].Text.Trim(),
                    Email = worksheet.Cells[row, 2].Text.Trim(),
                    CreateTime = worksheet.Cells[row, 3].GetValue<DateTime>()
                };

                var validationResult = ValidateUser(user, row);
                if (validationResult.IsValid)
                    result.ValidUsers.Add(user);
                else
                    result.Errors.AddRange(validationResult.ErrorMessages);
            }
        }
        return result;
    }
    
    private (bool IsValid, List<string> ErrorMessages) ValidateUser(User user, int excelRow)
    {
        var errors = new List<string>();

        // 必填字段检查
        if (string.IsNullOrEmpty(user.Username))
            errors.Add($"行 {excelRow}: 用户名不能为空");

        // 字段长度检查
        if (user.Username.Length > 32)
            errors.Add($"行 {excelRow}: 用户名长度超过32字符");

        if (user.Email?.Length > 32)
            errors.Add($"行 {excelRow}: 邮箱长度超过32字符");

        // 邮箱格式检查
        if (!string.IsNullOrEmpty(user.Email) && !new EmailAddressAttribute().IsValid(user.Email))
            errors.Add($"行 {excelRow}: 邮箱格式无效");

        return (errors.Count == 0, errors);
    }
}